<?php

/**
 * 
 * @project     : innoTweets 1.0
 * @author      : Dino (DBK)
 * 
 * @package     : API Apps
 * @description : Can create applications using the users of innoTweets
 *                
 * 
 */
if (!defined('BASEPATH')) {
  exit('No direct script access allowed');
}

class Api extends CI_Controller {

  public function __construct() {
    parent::__construct();
    $this->load->library('crypt');
    $this->load->library('user_agent');
  }

  public function index() {
    redirect();
  }

  public function get_token() {
    $req_token = preg_replace("/[^a-zA-Z0-9]+/", "", $this->input->get('req_token', TRUE));
    if (!empty($req_token)) {
      $validate_app = $this->validate_app($req_token);
      if (!empty($validate_app)) {
        echo trim($this->crypt->encrypt($req_token));
        return;
      }
    }
    return NULL;
  }

  public function get_auth() {
    $api_token = preg_replace("/[^a-zA-Z0-9]+/", "", $this->input->get('api_token', TRUE));
    if ($this->already_authorized($api_token)) {
      redirect('api/set_auth?api_token=' . $api_token);
      return;
    } else {
      $this->load->library('session');
      $this->load->library('user_session');
      $this->user_session->signout();
      redirect('signin?api_token=' . $api_token);
      return;
    }
  }

  public function set_auth() {
    $api_token = preg_replace("/[^a-zA-Z0-9]+/", "", $this->input->get('api_token', TRUE));
    if (!empty($api_token)) {
      $user_data = $this->get_current_user();
      if (empty($user_data) && (!$this->already_authorized($api_token))) {
        redirect('signin?api_token=' . $api_token);
        return;
      } else {
        $req_token = $this->crypt->decrypt($api_token);
        if (!empty($req_token)) {
          $validate_app = $this->validate_app($req_token);
          if (!empty($validate_app)) {
            $user_data['app_token'] = $validate_app['app_token'];
            $user_data['app_callback'] = $validate_app['app_callback'];
            $user_data_token = $this->crypt->encrypt(base64_encode(json_encode($user_data)));
            if (parse_url($validate_app['app_callback'], PHP_URL_QUERY)) {
              redirect($validate_app['app_callback'] . '&innotweets_user_token=' . $user_data_token);
            } else {
              redirect($validate_app['app_callback'] . '?innotweets_user_token=' . $user_data_token);
            }
            return;
          }
        }
      }
    }
    redirect();
    return;
  }

  public function get_data() {
    $response = array('status' => 0, 'msg' => NULL, 'data' => NULL);
    $user_token = preg_replace("/[^a-zA-Z0-9]+/", "", $this->input->get('user_token', TRUE));
    if (!empty($user_token)) {
      $user_token_dec = $this->crypt->decrypt($user_token);
      if (!empty($user_token_dec)) {
        $validate_app = $this->validate_app($user_token_dec);
        if (!empty($validate_app)) {
          if (!empty($validate_app['current_user_id'])) {
            $user_data = $this->get_user_by_id($validate_app['current_user_id']);
            if (!empty($user_data)) {
              $check_authorization = $this->check_authorization($validate_app['app_id'], $user_data['user_id']);
              if ($check_authorization) {
                $log_msg = $user_data['user_name'] . ' (' . $user_data['user_id'] . ') by ' . $validate_app['app_token'] . ' (' . $validate_app['app_name'] . ') via ' . $this->input->ip_address();
                system_log('api_apps', $log_msg);
                $response['status'] = 1;
                $response['msg'] = 'success';
                $response['data'] = $user_data;
              } else {
                $response['msg'] = 'User authorization failure';
              }
            } else {
              $response['msg'] = 'User doesnot exist or inactive';
            }
          } else {
            $response['msg'] = 'Unable to reterive user id from token';
          }
        } else {
          $response['msg'] = 'App not found';
        }
      } else {
        $response['msg'] = 'User token broken';
      }
    }
    echo @json_encode($response);
  }

  private function already_authorized($api_token = NULL) {
    $already_authorized = FALSE;
    if (!empty($api_token)) {
      $req_token = $this->crypt->decrypt($api_token);
      if (!empty($req_token)) {
        $validate_app = $this->validate_app($req_token);
        if (!empty($validate_app)) {
          $user_data = $this->get_current_user();
          if (!empty($user_data)) {
            $check_authorization = $this->check_authorization($validate_app['app_id'], $user_data['user_id']);
            if ($check_authorization) {
              $already_authorized = TRUE;
            }
          }
        }
      }
    }
    return $already_authorized;
  }

  private function validate_app($app_token = NULL) {
    if (!empty($app_token)) {
      $req_data = @json_decode(base64_decode($app_token));
      if (!empty($req_data)) {
        if (isset($req_data->app_token) && !empty($req_data->app_token) && isset($req_data->app_callback) && !empty($req_data->app_callback)) {
          $get_app_by_token = $this->api_model->get_app_by_token($req_data->app_token);
          if ($get_app_by_token['status'] == 1 && !empty($get_app_by_token['result'])) {
            $app_data = array();
            $app_data = $get_app_by_token['result'];
            $app_data['app_callback'] = $req_data->app_callback;
            if (isset($req_data->user_id)) {
              $app_data['current_user_id'] = $req_data->user_id;
            }
            return $app_data;
          }
        }
      }
    }
    return NULL;
  }

  private function check_authorization($app_id = NULL, $user_id = NULL) {
    if (!empty($app_id) && !empty($user_id)) {
      $get_app_authorization = $this->api_model->get_app_authorization($app_id, $user_id);
      if ($get_app_authorization['status'] == 1 && !empty($get_app_authorization['result'])) {
        return TRUE;
      }
    }
    return FALSE;
  }

  private function get_current_user() {
    $this->load->library('session');
    $this->load->library('user_session');
    $signuser = $this->user_session->signuser();
    $user_details = array();
    if (!empty($signuser)) {
      $user_details['user_id'] = $signuser['user_id'];
    }
    return $user_details;
  }

  private function get_user_by_id($user_id = NULL) {
    $get_user_by_id = $this->user_model->get_user_by_id($user_id);
    $user_details = array();
    if (!empty($get_user_by_id['result'])) {
      $user_details['user_id'] = $get_user_by_id['result']['user_id'];
      $user_details['user_name'] = $get_user_by_id['result']['user_name'];
      $user_details['user_display_name'] = $get_user_by_id['result']['user_display_name'];
      $user_details['user_likes_level'] = $get_user_by_id['result']['user_likes_level'];
      $user_details['user_gender'] = $get_user_by_id['result']['user_gender'];
      $user_details['user_position'] = $get_user_by_id['result']['user_position'];
      $user_details['user_skills'] = $get_user_by_id['result']['user_skills'];
      $user_details['user_hobbies'] = $get_user_by_id['result']['user_hobbies'];
      $user_details['user_place'] = $get_user_by_id['result']['user_place'];
      $user_details['user_profile_url'] = site_url('profile/' . $get_user_by_id['result']['user_name']);
      $user_details['user_image_url'] = site_url('assets/photos/' . $get_user_by_id['result']['user_image']);
    }
    return $user_details;
  }

  /**
   * Get user by username
   * 
   * @param type $username
   * @return type
   */
  public function get_user() {
    $api_data = array();
    $api_data['status'] = 0;
    $api_data['message'] = null;
    $api_data['data'] = null;
    $username = (string) $this->input->get('username', true);
    $password = (string) $this->input->get('password', true);
    if (!empty($username) && !empty($password)) {
      $get_user_by_id = $this->user_model->get_user_by_username($username, true);
      if (!empty($get_user_by_id['result'])) {
        if (($get_user_by_id['result']['user_password']) == md5($password)) {
          $user_details = array();
          $user_details['user_id'] = $get_user_by_id['result']['user_id'];
          $user_details['user_name'] = $get_user_by_id['result']['user_name'];
          $user_details['user_display_name'] = $get_user_by_id['result']['user_display_name'];
          $user_details['user_likes_level'] = $get_user_by_id['result']['user_likes_level'];
          $user_details['user_gender'] = $get_user_by_id['result']['user_gender'];
          $user_details['user_position'] = $get_user_by_id['result']['user_position'];
          $user_details['user_skills'] = $get_user_by_id['result']['user_skills'];
          $user_details['user_hobbies'] = $get_user_by_id['result']['user_hobbies'];
          $user_details['user_place'] = $get_user_by_id['result']['user_place'];
          $user_details['user_profile_url'] = site_url('profile/' . $get_user_by_id['result']['user_name']);
          $user_details['user_image_url'] = site_url('assets/photos/' . $get_user_by_id['result']['user_image']);
          $api_data['status'] = 1;
          $api_data['message'] = 'Success';
          $api_data['data'] = $user_details;
        } else {
          $api_data['message'] = 'Password incorrect';
        }
      } else {
        $api_data['message'] = 'User not found';
      }
    } else {
      $api_data['message'] = 'Username and password required';
    }
    die(json_encode($api_data));
  }

}

?>